package com.chiemy.cardview;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.util.Properties;
import java.util.concurrent.Semaphore;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.DisplayMetrics;

public class Utils {
	
	private Semaphore write_log_lock       = new Semaphore(1);
	
	public static boolean UI_ONLY_SURPPORT_LED = false;

	/**
	 * This method converts device specific pixels to device independent pixels.
	 * 
	 * @param px
	 *            A value in px (pixels) unit. Which we need to convert into db
	 * @param context
	 *            Context to get resources and device specific display metrics
	 * @return A float value to represent db equivalent to px value
	 */
	public float convertPixelsToDp(Context ctx, float px) {
		DisplayMetrics metrics = ctx.getResources().getDisplayMetrics();
		float dp = px / (metrics.densityDpi / 160f);
		return dp;

	}

	public static int convertDpToPixelInt(Context context, float dp) {

		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		int px = (int) (dp * (metrics.densityDpi / 160f));
		return px;
	}
	
	public static float convertDpToPixel(Context context, float dp) {

		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		float px = (float) (dp * (metrics.densityDpi / 160f));
		return px;
	}
	
	//get iniconfig
	public Properties loadConfig(Context context, String file) {
		Properties properties = new Properties();
		try {
			FileInputStream s = new FileInputStream(file);
			properties.load(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return properties;
	}

	//save ini config
	public void saveConfig(Context context, String file, Properties properties) {
		try {
			FileOutputStream s = new FileOutputStream(file, false);
			properties.store(s, "");
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	
	//读文件
	public byte [] readSDFile(String fileName) throws IOException {  

	        File file = new File(fileName);  

	        FileInputStream fis = new FileInputStream(file);  

	        int length = fis.available(); 

	         byte [] buffer = new byte[length]; 
	         fis.read(buffer);     

	         //Object res = EncodingUtils.getString(buffer, "UTF-8"); 

	         fis.close();     
	         return buffer;  
	}  
	

	//写文件
	public void writeSDFile(String fileName, String write_str) throws IOException{  

	        File file = new File(fileName);  

	        FileOutputStream fos = new FileOutputStream(file);  

	        byte [] bytes = write_str.getBytes(); 

	        fos.write(bytes); 

	        fos.close(); 
	} 
	
	
	public void writeSDFile(String fileName, byte[] bytes) throws IOException{  

        File file = new File(fileName);  

        FileOutputStream fos = new FileOutputStream(file);  

        fos.write(bytes); 

        fos.close(); 
	}
	
	
	public void writeSDFileAppend(String fileName, String content){  

		try {
			write_log_lock.acquire();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		FileWriter file;
		try {
			file = new FileWriter (fileName, true);
			file.write(content); 

			file.close(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  

        //FileOutputStream fos = new FileOutputStream(file);  
		write_log_lock.release();
		
	}
	
	
	public static void int4_to_bytearray(int src, byte[] dst)
	{
		if(dst == null || dst.length < 4)
			return ;
		dst[0] = (byte) (src & 0xff);
		dst[1] = (byte) (src >> 8 & 0xff);
		dst[2] = (byte) (src >> 16 & 0xff);
		dst[3] = (byte) (src >> 24 & 0xff);
	}
	
	
	public static void uint32_to_bytearray(long src, byte[] dst)
	{
		if(dst == null || dst.length < 4)
			return ;
		dst[0] = (byte) (src & 0xff);
		dst[1] = (byte) (src >> 8 & 0xff);
		dst[2] = (byte) (src >> 16 & 0xff);
		dst[3] = (byte) (src >> 24 & 0xff);
	}
	
	public static void uint16_to_bytearray(long src, byte[] dst)
	{
		if(dst == null || dst.length < 2)
			return ;
		dst[0] = (byte) (src & 0xff);
		dst[1] = (byte) (src >> 8 & 0xff);
	}
	
	public static int bytearray_to_int4(byte[] src)
	{
		int tmp = 0;
		if(src == null || src.length != 4)
			return 0;
		tmp = ((int)src[0] & 0xff) | ((int)src[1] & 0xff) << 8 | ((int)src[2] & 0xff) << 16 | ((int)src[3] & 0xff) << 24;
		return tmp;
	}
	
	
	public static int MSB_Bytearray_2_Int4(byte[] src)
	{
		int tmp = 0;
		if(src == null || src.length != 4)
			return 0;
		tmp = ((int)src[3] & 0xff) | ((int)src[2] & 0xff) << 8 | ((int)src[1] & 0xff) << 16 | ((int)src[0] & 0xff) << 24;
		return tmp;
	}
	
	public static void java_memset (byte[] data, int pos, byte value, int read_length){
		if(data.length < (pos+read_length))
			return ;
		int i = 0;
		for(i = pos; i < read_length; i++)
			data[i] = 0;
	}
	
	public static boolean bytearraycmp(byte[] src1, byte[] src2)
	{
		if(src1 == null || src2 == null)
			return false;
		if(src1.length != src2.length)
			return false;
		for (int i = 0; i < src1.length; i++)
			if(src1[i] != src2[i])
				return false;
		return true;
	}
	
	/** 
     * byte数组转换成16进制字符串 
     * @param src 
     * @return 
     */  
    public static String bytesToHexString(byte[] src){
    	StringBuilder stringBuilder = new StringBuilder();       
    	if (src == null || src.length <= 0) {       
    		return null;       
    	}       
    	for (int i = 0; i < src.length; i++) {       
    		int v = src[i] & 0xFF;       
    		String hv = Integer.toHexString(v);       
    		if (hv.length() < 2) {       
    			stringBuilder.append(0);       
    		}       
    		stringBuilder.append(hv+" ");       
    	}       
    	return stringBuilder.toString();       
    }


	/**
	 * HexString to Byte Array
	 * @param hexString
	 * @return
	 */
	public static byte[] toByteArray(String hexString) {
		if (hexString.isEmpty())
			throw new IllegalArgumentException("this hexString must not be empty");

		hexString = hexString.toLowerCase();
		final byte[] byteArray = new byte[hexString.length() / 2];
		int k = 0;
		for (int i = 0; i < byteArray.length; i++) {//因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
			byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
			byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
			byteArray[i] = (byte) (high << 4 | low);
			k += 2;
		}
		return byteArray;
	}


    public static void swap_byte_array(byte[] data)
    {
    	if(data == null || data.length == 0)
    		return;
    	int j = data.length - 1;
    	for (int i = 0 ; i < data.length/2 ;i++ ){
    		byte tmp = data[i];
    		data[i] = data[j];
    		data[j] = tmp;
    		j--;
    	}
    	
    }
}
